package cz.najman.emdroid.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import cz.najman.emdroid.listener.OnDataUpdatedListener;

/**
 * @author  Lukáš Najman
 */
public class ForwardingResultReceiver extends ResultReceiver {

	private Map<String,OnDataUpdatedListener> mListeners;
	
	public ForwardingResultReceiver(Handler handler) {
		super(handler);	
		mListeners = new HashMap<String, OnDataUpdatedListener>();
	}
	
	public ForwardingResultReceiver(Handler handler, Map<String,OnDataUpdatedListener> listener) {
		super(handler);
		mListeners = listener;
	}
	
	@Override
	protected void onReceiveResult(int statusCode, Bundle resultData) {
		Iterator<String> iterator = mListeners.keySet().iterator();
		Class objectClass = (Class) resultData.getSerializable(UpdaterService.OBJECT);
		
			OnDataUpdatedListener listener = mListeners.get(objectClass.getCanonicalName());
			if(listener != null){
				listener.fireDataUpdated(statusCode, objectClass);
			}		
	}

	/**
	 * @return  the mListeners
	 */
	public Map<String, OnDataUpdatedListener> getListeners() {
		return mListeners;
	}

	/**
	 * @param mListeners  the mListeners to set
	 */
	public void setListeners(Map<String, OnDataUpdatedListener> mListeners) {
		this.mListeners = mListeners;
	}
	
	public boolean registerListener(String tag, OnDataUpdatedListener listener){
		Object o = mListeners.put(tag, listener);
		if(o == null)
			return false;
		return true;
	}
	
	public boolean unregisterListener(String tag){
		Object o = mListeners.remove(tag);
		if(o == null)
			return false;
		return true;
	}
	
}
	

